using System;
using System.Data.OleDb;
using System.Text;

namespace Copperline.Escriba
{
	/// <summary>
	/// Summary description for DbLogger.
	/// </summary>
	public class DbLogger : LoggerBase
	{
		public DbLogger()
		{
			this.Connection = String.Empty;
			this.Filter = new SeverityFilter( ESeverity.debug, ETrigger.threshold );
		}

		public DbLogger( string sConnection )
		{
			this.Connection = sConnection;
			this.Filter = new SeverityFilter( ESeverity.debug, ETrigger.threshold );
		}

		public DbLogger( string sConnection, ESeverity severity, ETrigger trigger )
		{
			this.Connection = sConnection;
			this.Filter = new SeverityFilter( severity, trigger );
		}

		private string connection;
		public string Connection
		{
			get { return connection; }
			set { connection = value; }
		}

		public override void Write( LogEntry le )
		{
			if( le == null )
				return;

			if( !Filter.HasRequiredSeverity( le.Severity ) )
				return;

			if( Connection == null || Connection.Trim().Equals(String.Empty) )
			{
				Fault = true;
			}
			else
			{
				OleDbConnection conn = null;
				try
				{
					conn = new OleDbConnection( Connection );
					conn.Open();
					OleDbCommand cmd = new OleDbCommand();
					cmd.Connection = conn;
					cmd.CommandType = System.Data.CommandType.StoredProcedure;
					cmd.CommandText = "InsertBasicLogEntry";
					cmd.Parameters.Add( "Severity", (int)le.Severity );
					cmd.Parameters.Add( "Entry", le.Entry );
					cmd.ExecuteNonQuery();
				}
				catch( Exception ex )
				{
					Fault = true;
					LastError = new EscribaException( "Cannot write logEntry to " + Connection, ex );
				}
				finally
				{
					if( conn != null )
						conn.Close();
				}
			}
		}
	}
}
